# -*- coding:utf-8 -*-
# author: lawaiter
# time: 2020/6/21
# brief:


# from PyQt5 import QtWidgets, QtCore, QtMultimedia
# import sys
#
# app = QtWidgets.QApplication(sys.argv)
# url = QtCore.QUrl.fromLocalFile(r"C:\Users\lawaiter\CodeRepos\pythonproject\pyqt5First\static\song\Too Proud.FLAC")
# content = QtMultimedia.QMediaContent(url)
# player = QtMultimedia.QMediaPlayer()
# player.setMedia(content)
# player.setVolume(50.0)
# player.play()
# print(QtMultimedia.QMediaPlayer.MediaStatus())
# sys.exit(app.exec())








#
# from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia
# from PyQt5.QtCore import QUrl, Qt
# from PyQt5.QtWidgets import QGridLayout
# import sys
#
#
# class MainUi(QtWidgets.QMainWindow):
#
#     def __init__(self):
#         super().__init__()
#         self.init_ui()
#
#     def init_ui(self):
#         button1 = QtWidgets.QPushButton("button1",self)
#         button1.clicked.connect(self.playmusic)
#         url = QUrl.fromLocalFile(r"C:\Users\lawaiter\CodeRepos\pythonproject\pyqt5First\static\song\胡伟立 - 勇往直前.mp3")
#         content = QtMultimedia.QMediaContent(url)
#         self.player = QtMultimedia.QMediaPlayer()
#         self.player.setMedia(content)
#         button1.clicked.connect(self.playmusic)
#
#     def playmusic(self):
#         self.player.play()
#
#
# def main():
#     app = QtWidgets.QApplication(sys.argv)
#     gui = MainUi()
#     gui.show()
#     print(gui.player.MediaStatus())
#     sys.exit(app.exec_())
#
#
# if __name__ == '__main__':
#     main()


# !usr/bin/python3
# -*- coding:utf-8 -*-
# author:SingWeek
#
# from PyQt5.QtWidgets import *
# from PyQt5.QtCore import *
# import sys, time
#
#
# class MyTable(QTableWidget):
#     def __init__(self, parent=None):
#         super(MyTable, self).__init__(parent)
#         self.setWindowTitle("Test")  # 设置表格名称
#         # self.resize(600, 200)  # 设置表格尺寸（整体大小）
#         self.Config_Set = QGroupBox("Test")
#         self.Text = QLineEdit("显示")
#         self.CBtn = QPushButton("开始")
#         self.Click = QPushButton("打印")
#         self.NTime = QLineEdit("")
#         layout = QGridLayout()
#         layout.addWidget(self.CBtn, 1, 1)
#         layout.addWidget(self.Text, 2, 1)
#         layout.addWidget(self.Click, 3, 1)
#         layout.addWidget(self.NTime, 4, 1)
#         self.Config_Set.setLayout(layout)
#
#         mainLayout = QVBoxLayout()
#         hboxLayout = QHBoxLayout()
#         hboxLayout.addStretch()
#         hboxLayout.addWidget(self.Config_Set)  # 横向添加表格块
#         mainLayout.addLayout(hboxLayout)
#         self.setLayout(mainLayout)
#
#         self.CBtn.clicked.connect(self.Btn)
#         self.Click.clicked.connect(self.Print)
#
#     def Print(self):
#         self.NTime.setText("当前系统时间" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
#         print("当前系统时间" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
#
#     def Btn(self):
#         calcnum = 100000
#         update_data_thread = UpdateData(calcnum)  #
#         update_data_thread.update_date.connect(self.update_item_data)  # 链接信号
#         update_data_thread.run()
#
#     def update_item_data(self, data):
#         """更新内容"""
#         self.Text.setText(data)
#
#
# class UpdateData(QThread):
#     """界面和 运行相分离，通过信号与槽来进行参数传递"""
#     update_date = pyqtSignal(str)  # pyqt5 支持python3的str，没有Qstring
#
#     def __init__(self, data, parent=None):
#         super(UpdateData, self).__init__(parent)
#         self.data = data
#
#     def run(self):
#         calc(self.data, self.update_date)
#
#
# def calc(data, update_date):
#     """
#     下面可以是其他相应的功能函数
#     :param update_date:
#     :return:
#     """
#     cnt = 0
#     while True:
#         cnt += 1
#         update_date.emit(str(cnt))  # 发射信号
#         # time.sleep(1)
#         if cnt >= data:
#             cnt = 0
#         QApplication.processEvents()  # 刷新界面，避免卡顿
#
#
# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     myTable = MyTable()
#     myTable.show()
#     app.exit(app.exec_())





# from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
# from PyQt5.QtMultimedia import *
# from PyQt5.QtCore import *
# from PyQt5.QtGui import *
#
# from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
# from matplotlib.animation import FuncAnimation
# from scipy.signal import detrend
# from pydub import AudioSegment
#
# import matplotlib.pyplot as plt
# import numpy as np
# import struct
# import wave
# import os
# import sys
# import time
#
# chunk = 1024
#
# # 将该路径文件从mp3转为wav
# def change_format(path):
#     new_path = path.replace('mp3', 'wav')
#     # 将mp3文件转换成wav
#     sound = AudioSegment.from_mp3(path)
#     sound.export(new_path, format="wav")
#
#
# # FigureCanvas 对象
# class MyMplCanvas(FigureCanvas):
#     def __init__(self, parent=None, width=5, height=4, dpi=100):
#         fig = plt.figure(figsize=(width, height), dpi=dpi, facecolor='#f0f0f0')       # facecolor 背景色
#         self.ax = fig.gca(projection='polar')
#         self.ax.set_axis_off()
#         self.ln, = self.ax.plot([], [])
#         FigureCanvas.__init__(self, fig)
#
#
# class MyWindow(QMainWindow, Ui_MainWindow):
#     def __init__(self):
#         super(MyWindow, self).__init__()
#         self.setupUi(self)
#         self.initialize()
#
#     '''初始化'''
#     def initialize(self):
#         self.setWindowTitle("音乐播放器^_^")
#         self.setWindowIcon(QIcon('icon/音乐.png'))
#         self.fileName = ""
#         self.cur_song = ''
#         self.is_pause = True
#         self.y_temp = np.zeros(chunk)
#
#         self.playlist = QMediaPlaylist()  # 播放列表
#         self.playlist.setPlaybackMode(QMediaPlaylist.Loop)  # 列表循环
#         self.player = QMediaPlayer(self)
#         self.player.setPlaylist(self.playlist)
#         self.player.setVolume(50.0)
#
#         # 按键
#         self.btn_openFile.clicked.connect(lambda: self.btn_openFile_click())
#         self.btn_start.clicked.connect(lambda: self.btn_start_click())
#
#         # 进度条
#         self.slider_time.sliderMoved[int].connect(lambda: self.player.setPosition(self.slider_time.value()))
#
#         # 计时器:控制进度条和进度时间
#         self.timer = QTimer(self)
#         self.timer.start(1000)
#         self.timer.timeout.connect(self.player_timer)
#
#         # 音乐可视化
#         self.isualization()
#
#     # 坐标初始化
#     def init_draw(self):
#         self.canvas.ax.set_ylim(-0.1, 0.1)
#         self.canvas.ln.set_data(np.linspace(0, 2 * np.pi, chunk), np.zeros(chunk))
#
#
#         return self.canvas.ln,
#
#     # 坐标更新
#     def update_line(self, frame):
#         if self.is_pause is False:
#             data = self.wf.readframes(chunk)
#             data_int = struct.unpack(str(chunk * 4) + 'B', data)
#             y_detrend = detrend(data_int)
#             yft = np.abs(np.fft.fft(y_detrend))
#             y_vals = yft[:chunk] / (chunk * chunk * 4)
#             ind = np.where(y_vals > (np.max(y_vals) + np.min(y_vals)) / 2)
#             y_vals[ind[0]] *= 3
#             self.y_temp = y_vals
#         else:
#             y_vals = self.y_temp       # 当暂停时，保存的是上一次的值
#
#         self.canvas.ln.set_ydata(y_vals)
#         return self.canvas.ln,
#
#     # 音乐可视化
#     def isualization(self):
#         self.canvas = MyMplCanvas(self.container, width=6, height=6, dpi=100)
#         self.container.addWidget(self.canvas)  # 6
#         self.ani = FuncAnimation(self.canvas.figure, self.update_line, init_func=self.init_draw, interval=32, blit=True)
#
#     # 设置进度条和播放时间
#     def player_timer(self):
#         self.slider_time.setMinimum(0)
#         self.slider_time.setMaximum(self.player.duration())
#         self.slider_time.setValue(self.slider_time.value() + 1000)
#
#         self.lab_time.setText(time.strftime('%M:%S', time.localtime(self.player.position() / 1000)))
#         self.lab_duration.setText(time.strftime('%M:%S', time.localtime(self.player.duration() / 1000)))
#
#         # 进度条满了之后回零
#         if self.player.duration() == self.slider_time.value():
#             self.slider_time.setValue(0)
#
#     # 打开音乐文件，并添加至playlist
#     def btn_openFile_click(self):
#         self.playlist.clear()     # 读取歌曲前，清空playlist
#         self.fileName, filetype = QFileDialog.getOpenFileName(self, '选择文件', '', '音频文件 (*.mp3; *.wav)')
#         if len(self.fileName) == 0:
#             print("取消选择")
#             return
#         else:
#             print('当前歌曲路径：' + self.fileName)
#             self.cur_song = os.path.basename(self.fileName)
#             self.lab_name.setText(self.cur_song)
#
#             # 如果是mp3格式，则将mp3转换wav，保存到同一目录下
#             if self.cur_song[-3:] == 'mp3':
#                 change_format(self.fileName)
#                 self.fileName = self.fileName.replace('mp3', 'wav')
#                 print('new'+ self.fileName)
#
#             # 将音频文件添加到playlist
#             self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(self.fileName)))
#
#             # 可视化部分wave
#             self.wf = wave.open(self.fileName)
#
#         # 正在播放音乐时，中断播放
#         if self.is_pause is False:
#             self.player.pause()
#             self.btn_start.setText('播放')
#
#     def btn_start_click(self):
#
#         if self.is_pause:
#             self.is_pause = False
#             self.player.play()
#             self.btn_start.setText('暂停')
#             print('当前播放歌曲： ' + self.cur_song)
#         else:
#             self.is_pause = True
#             self.player.pause()
#             self.btn_start.setText('播放')
#
#
# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     myWin = MyWindow()
#     myWin.show()
#     sys.exit(app.exec_())
#





# import matplotlib.pyplot as plt
# from scipy.signal import detrend
# # from scipy.fftpack import fft
# import numpy as np
# import pyaudio
# from _tkinter import TclError
# import struct
# import wave
# # import librosa
# from pydub import AudioSegment
# from matplotlib.animation import FuncAnimation
#
# chunk = 600
# p = pyaudio.PyAudio()
# # sound = AudioSegment.from_file(file='../Music/xxx.mp3')
# # rdata = sound.get_array_of_samples()
# wf = wave.open('六三四-朝.wav')
# stream = p.open(
#     format=8,
#     channels=wf.getnchannels(),
#     rate=wf.getframerate(),
#     # input=True,
#     output=True,
#     # frames_per_buffer=chunk
# )
#
# fig = plt.figure()
# ax = fig.gca()
# ax.set_ylim(0, 1)
# ax.set_axis_off()
# lf = ax.stem(np.linspace(20, 20000, chunk), np.zeros(chunk), basefmt=':', use_line_collection=True)
# # lf.markerline.set_color([0.8, 0.2, 0, 0.5])
# lf.markerline.set_color([0.3,0.4,0.5,0.6])
# # lf.markerline.set_color('yellow')
#
# def init():
#     stream.start_stream()
#     return lf
#
#
# def update(frame):
#     if stream.is_active():
#         data = wf.readframes(chunk)
#         stream.write(data)
#         data_int = struct.unpack(str(chunk * 4) + 'B', data)
#         y_detrend = detrend(data_int)
#         yft = np.abs(np.fft.fft(y_detrend))
#         y_vals = yft[:chunk] / (chunk * chunk)
#         ind = np.where(y_vals > (np.max(y_vals) + np.min(y_vals)) / 2)
#         y_vals[ind[0]] *= 4
#         # print(y_vals)
#         lf.markerline.set_ydata(y_vals)
#     return lf
#
#
# ani = FuncAnimation(fig, update, frames=None,
#                     init_func=init, interval=0, blit=True)
# plt.show()






# from PIL.ImageQt import rgb
# from PyQt5.QtWidgets import QPushButton,QWidget,QApplication,QGridLayout,QListWidget,QLineEdit
# import pyqtgraph as pg
# import sys
# import numpy as np
#
#
# class Example(QWidget):
#     def __init__(self):
#         super(Example, self).__init__()
#         self.initUI()
#         self.linePlot()
#         self.scatterPlot()
#         self.three_curves()
#
#     def initUI(self):
#         self.setGeometry(400,400,800,620)
#         self.setWindowTitle("pyqtgraph快速入门")
#
#         ## 创建一些小部件放在顶级窗口中
#         btn = QPushButton('press me')
#         text = QLineEdit('enter text')
#         listw = QListWidget()
#         listw.addItems(["aa", "bb", "cc"])
#
#         self.gridLayout = QGridLayout(self)
#         ## 将部件添加到布局中的适当位置
#         self.gridLayout.addWidget(btn, 0, 0)
#         self.gridLayout.addWidget(text, 1, 0)
#         self.gridLayout.addWidget(listw, 2, 0)
#
#         self.setLayout(self.gridLayout)
#
#     def linePlot(self):
#         plt1 = pg.PlotWidget()
#         plt1.plot([i for i in range(10)], [i * i for i in range(10)])
#         self.gridLayout.addWidget(plt1, 0, 1, 1, 1)
#
#     def scatterPlot(self):
#         plt2 = pg.PlotWidget()
#         plt2.setBackground(rgb(217, 247, 255, 0))
#         x = np.random.normal(size=1000)
#         y = np.random.normal(size=1000)
#         plt2.plot(x, y, pen=None, symbol="o")
#         self.gridLayout.addWidget(plt2, 1, 1, 1, 1)
#
#     def three_curves(self):
#         plt3 = pg.PlotWidget(title="Three plot curves")
#         x = np.arange(1000)
#         y = np.random.normal(size=(3, 1000))
#         for i in range(3):
#             plt3.plot(x, y[i], pen=(i, 3))  ## setting pen=(i,3) 自动创建3个不同颜色的笔
#         self.gridLayout.addWidget(plt3, 2, 1, 1, 1)
#
# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     ex = Example()
#     ex.show()
#     sys.exit(app.exec_())



# TODO 这是使用Pygame界面可以使用的
# import warnings
#
# warnings.simplefilter("ignore", DeprecationWarning)#防止报警告
# import pyaudio
# import wave
from pydub import AudioSegment
#
# import numpy as np
# import pygame
# from pygame.locals import *
# from PyQt5.QtMultimedia import QMediaPlayer
# from PyQt5.QtCore import QFile
#
# CHUNK = 1024  # 我把它理解为缓冲流
#
# sound = AudioSegment.from_mp3("./胡伟立勇往直前.mp3")
# sound.export("./胡伟立勇往直前.wav", format='wav')
# wf = wave.open("./六三四-朝.wav", 'rb')  # 以只读的方式打开"1qom8-vi8uq.wav"文件
#
# # 创建播放器
# p = pyaudio.PyAudio()
# # 打开数据流  output=True表示音频输出
# stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
#                 channels=wf.getnchannels(),  # 设置声道数
#                 rate=wf.getframerate(),  # 设置流的频率
#                 output=True,
#                 )
#
# data = wf.readframes(CHUNK)  # 音频数据初始化
#
# screen = pygame.display.set_mode((850, 400), 0, 32)#窗口大小为(850,400)
# pygame.init()#pygame初始化
# pygame.mixer.init()
# pl = QMediaPlayer()
#
#
#
# pygame.display.set_caption('实时频域')#设置窗口标题
# while data != '':  # 直到音频放完
# #
#     stream.write(data) # 播放缓冲流的音频
#     data = wf.readframes(CHUNK)  # 更新data
#
#     numpydata = np.fromstring(data, dtype=np.int16)  # 把data由字符串以十六进制的方式转变为数组
#     transforamed = np.real(np.fft.fft(numpydata))  # 傅里叶变换获取实数部分
#     screen.fill((0, 0, 0))#清空屏幕
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             pygame.quit()       #这段代码防止无响应
#     count = 50  # 设置间隔区
#     print("size=", transforamed)
#     for n in range(0, transforamed.size, count):  # 从频域中的2048个数据中没隔count个数据中选取一条
#         hight = abs(int(transforamed[n] / 10000))  # 对这么多数据取整和绝对值
#         pygame.draw.rect(screen,(255,123,255, 123),Rect((20*n/count,400),(20,-hight)))#画矩形
#
#     pygame.display.update()#更新屏幕
#
# stream.stop_stream()
# stream.close()
# #关闭流
# p.terminate()




# TODO 这是可以出现的音乐频谱，但是目前一个音乐会播放，二是动态特效显示会有坐标轴
# import numpy as np
# import pyqtgraph as pg
# import wave
# app = pg.mkQApp()
#
# win = pg.GraphicsWindow()
# win.setWindowTitle(u'pyqtgraph plot demo')
# win.resize(600, 400)
# p = win.addPlot()
# p.showGrid(x=False, y=False)
# p.setLabel(axis='left', text=None)
# p.setLabel(axis='bottom', text=None)
# p.addLegend()
#
# curve3 = p.plot(pen='g', name='y3')
# Fs = 1024.0 #采样频率
# N = 1024    #采样点数
# f0 = 5.0    #信号频率
# pha = 0     #初始相位
# t = np.arange(N) / Fs   #时间向量
# hight1 = np.array(2048)
#
#
# def plotData(time, tim2):
#     print(time, tim2)
#     global pha
#     pha += 10
#     import pyaudio
#     CHUNK = 1024  # 我把它理解为缓冲流
#
#     wf = wave.open("./六三四-朝.wav", 'rb')  # 以只读的方式打开"1qom8-vi8uq.wav"文件
#
#         # 创建播放器
#     p = pyaudio.PyAudio()
#         # 打开数据流  output=True表示音频输出
#     stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
#                         channels=wf.getnchannels(),  # 设置声道数
#                         rate=wf.getframerate(),  # 设置流的频率
#                         output=True,
#                         )
#
#     data = wf.readframes(CHUNK)  # 音频数据初始化
#     while data !="" :
#         global hight1
#         stream.write(data)
#         data = wf.readframes(CHUNK)  # 更新data
#         print("data=", data)
#         print("type=", type(data))
#         numpydata = np.fromstring(data, dtype=np.int16)  # 把data由字符串以十六进制的方式转变为数组
#         transforamed = np.real(np.fft.fft(numpydata))  # 傅里叶变换获取实数部分
#         hight1 = transforamed
#         print("size=", transforamed)
#         count = 50  # 设置间隔区
#         for n in range(0, transforamed.size, count):  # 从频域中的2048个数据中没隔count个数据中选取一条
#             hight = abs(int(transforamed[n] / 10000))  # 对这么多数据取整和绝对值
#     stream.stop_stream()
#     stream.close()
#     #关闭流
#     p.terminate()
#
#
# def update(w=None, e=None):
#     curve3.setData(np.arange(2048), np.abs(hight1))
#     print("a=", hight1)
#
# import _thread
#
# _thread.start_new_thread(plotData, (1, 2,))
# _thread.start_new_thread(update, (3, 4))
# timer = pg.QtCore.QTimer()
# timer.timeout.connect(update)
# timer.start(50)
# app.exec_()



# TODO 专业的音频分析库
# import librosa
# import librosa.display
# import matplotlib.pyplot as plt
# y, sr = librosa.load("./六三四-朝.wav", sr=None, mono=True, offset=1,  duration=1)
# print(type(y))
# print(len(y))
# print(sr)
# librosa.display.waveplot(y, sr=sr)
# plt.show()




# TODO 这是可以使用的音乐动态效果，但是播放时间不等于已知的歌曲时间
# import numpy as np
# import pyqtgraph as pg
# import wave
#
# from pydub import AudioSegment
#
# app = pg.mkQApp()
#
# win = pg.GraphicsWindow()
# win.setWindowTitle(u'pyqtgraph plot demo')
# win.resize(600, 400)
# p = win.addPlot()
# p.showGrid(x=False, y=False)
# p.setLabel(axis='left', text=None)
# p.setLabel(axis='bottom', text=None)
# p.addLegend()
#
# curve3 = p.plot(pen='g', name='y3')
# Fs = 1024.0 #采样频率
# N = 1024    #采样点数
# f0 = 5.0    #信号频率
# pha = 0     #初始相位
# t = np.arange(N) / Fs   #时间向量
# hight1 = np.array(3072)
# import os
#
#
# sound = AudioSegment.from_wav("./胡伟立勇往直前.wav")
# second2 = sound.duration_seconds
# print("s2", second2)
#
# size = os.path.getsize("./胡伟立勇往直前.wav")
# print("size2=", size)
#
#
# CHUNK_PRE = size / (second2 * 1000) # 我把它理解为缓冲流
# print("CHUNK_PRE=", CHUNK_PRE)
#
# count = 50
#
#
# CHUNK = int(count * CHUNK_PRE)
#
#
# def read():
#     global CHUNK, curve3
#
#     # with open("./誓い.wav", 'rb') as song:
#     with wave.open("胡伟立勇往直前.wav", 'rb') as song:
#         data = song.readframes(CHUNK)
#         print("won2")
#         while data:
#             print("s2", second2)
#             print("size2=", size)
#             print("CHUNK_PRE=", CHUNK_PRE)
#             print("CHUNK=", CHUNK)
#             print("won1=", song.getparams())
#             print("won3")
#             data = song.readframes(CHUNK)  # 更新data
#             print("won4")
#             yield data
#         song.close()
#
#
#
# def use(q=None, b=None):
#     for i in read():
#         print("data=", i)
#         print("type=", type(i))
#         numpydata = np.fromstring(i, dtype=np.int16)
#         print("numpydata=", numpydata)
#         print("Type-numpydata=", type(numpydata))
#         transforamed = np.real(np.fft.fft(numpydata))
#         print("transforamed=", transforamed)
#         print("Type-transforamed=", type(transforamed))
#         print("Size-transforamed=", transforamed.size)
#         global hight1
#         hight1 = transforamed
#
#
# def draw(a=None, b=None):
#     print("hight1=", np.abs(hight1))
#     w = [abs(hight1[i]) for i in range(0, hight1.size)]
#     curve3.setData(np.arange(len(w)), w)
#
# import _thread
#
# _thread.start_new_thread(use, (1, 2,))
# _thread.start_new_thread(draw, (3, 4))
# timer = pg.QtCore.QTimer()
# timer.timeout.connect(draw)
# timer.start(count)
#
#
# app.exec_()



import requests

a = requests.get("http://music.163.com/api/search/pc/?type=1&s=爱你一万年").json()
print(a['result'])
